var formatNumber = function (n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

var getRegExp = function (reg, flag) {
  return new RegExp(reg, flag)
}

var getDate = function (param) {
  return new Date(param)
}

var regYear = getRegExp("(y+)", "i");

// 时间戳格式化为字符串
var dateFormat = function (timestamp, format) {
  if (!timestamp) return null
  if (!format) {
    format = "yyyy-MM-dd hh:mm:ss";
  }
  timestamp = parseInt(timestamp);
  // 通过getDate()方法获取date类型的时间
  var realDate = getDate(timestamp);

  function timeFormat(num) {
    return num < 10 ? '0' + num : num;
  }
  var date = [
    ["M+", timeFormat(realDate.getMonth() + 1)],
    ["d+", timeFormat(realDate.getDate())],
    ["h+", timeFormat(realDate.getHours())],
    ["m+", timeFormat(realDate.getMinutes())],
    ["s+", timeFormat(realDate.getSeconds())],
    ["q+", Math.floor((realDate.getMonth() + 3) / 3)],
    ["S+", realDate.getMilliseconds()],
  ];
  var reg1 = regYear.exec(format);
  if (reg1) {
    format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length));
  }
  for (var i = 0; i < date.length; i++) {
    var k = date[i][0];
    var v = date[i][1];
    // getRegExp初始化一个正则表达式对象
    var reg2 = getRegExp("(" + k + ")").exec(format);
    if (reg2) {
      format = format.replace(reg2[1], reg2[1].length == 1 ?
        v : ("00" + v).substring(("" + v).length));
    }
  }
  return format;
}

// 把格式化的日期时间字符串转换成时间戳
function parse(strDate) {
  if (!strDate) return null
  const fmt1 = strDate.substring(0, 19);
  var reg = getRegExp("-", "g");
  const fmt2 = fmt1.replace(reg, '/');
  return getDate(fmt2).getTime();
}

export const dateTool = {
  format: dateFormat, // 时间戳格式化为字符串
  parse: parse, // 把格式化的日期时间字符串转换成时间戳
  readable(timestamp) {
    const now = this.yearMonthDay(new Date()),
      target = this.yearMonthDay(new Date(timestamp))
    let result = (now.year != target.year ? target.year : '') // year
    result = (() => { // month day
      if (result == '' && now.month == target.month) return this.descDay(now.date, target.date)
      else return (result ? `${result}.` : '') + this.format(timestamp, 'MM.dd ')
    })()
    return result + this.format(timestamp, 'hh:mm') // min:sec
  },
  yearMonthDay(date) {
    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      day: date.getDate(),
      date
    }
  },
  descDay(now, target) {
    if (now.getDate() == target.getDate()) return '今天'
    if (new Date(target.getTime() + 3600000 * 24).getDate() == now.getDate()) return '昨天'
    if (new Date(target.getTime() - 3600000 * 24).getDate() == now.getDate()) return '明天'
    return this.format(target.getTime(), 'MM.dd ')
  },
  dayEnd(timestamp) {
    const t = new Date(timestamp)
    return new Date(t.getFullYear(), t.getMonth(), t.getDate(), 23, 59, 59, 999).getTime()
  }
}